package com.hz.eduService.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hz.apiService.client.StudentApi;
import com.hz.apiService.client.TeacherApi;
import com.hz.apiService.model.domain.StudentDTO;
import com.hz.apiService.model.enums.ApiResponseCodeEnum;
import com.hz.apiService.model.request.ApiResponse;
import com.hz.eduService.domain.Course;
import com.hz.eduService.domain.UserCourse;
import com.hz.eduService.domain.dto.UserSelectCourseDTO;
import com.hz.eduService.mapper.CourseMapper;
import com.hz.eduService.mapper.UserCourseMapper;
import com.hz.eduService.service.UserCourseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author li
 * @description 针对表【user_courses(学生选课表)】的数据库操作Service实现
 * @createDate 2023-09-23 17:14:14
 */
@Service
public class UserCourseServiceImpl extends ServiceImpl<UserCourseMapper, UserCourse> implements UserCourseService {
    @Resource
    StudentApi studentApi;


    @Resource
    UserCourseMapper userCourseMapper;
    @Resource
    CourseMapper courseMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<UserCourse> viewSelectedStudents(Integer courseId) {
        Map<String, Object> map = new HashMap<>();
        map.put("course_id", courseId);
        return userCourseMapper.selectByMap(map);
    }

    @Override
    public UserCourse checkScore(Integer id, Integer userScore, Integer studentUserId) {
        UserCourse userCourse = new UserCourse();
        userCourse.setId(id);
        userCourse.setStudentUserId(studentUserId);
        userCourse.setUserScore(userScore);
        userCourseMapper.updateById(userCourse);
        return userCourse;
    }

    @Override
    public boolean applyReExam(Integer id, Integer userScore, Integer passScore) {
        UserCourse userCourse = new UserCourse();
        Course course = new Course();
        course.setPassScore(passScore);
        userCourse.setId(id);
        userCourse.setUserScore(userScore);

        return userScore >= passScore;
    }

    @Override
    public UserCourse myScore(Integer id) {

        return userCourseMapper.selectById(id);
    }

    @Override
    public Boolean addUserCourse(UserCourse userCourse) {
        return this.save(userCourse);
    }

    @Override
    public int selectCourse(Integer userId, Integer courseId) {

        UserCourse userCourse = userCourseMapper.selectByUserIdAndCourseId(userId, courseId);
        Course course = courseMapper.selectById(courseId);
        // 课程是否存在
        if (course == null)
            return 0;

        Map<String, Object> map = new HashMap<>();
        map.put("course_id", course.getId());
        List<UserCourse> userCourses = userCourseMapper.selectByMap(map);

        // 判断学生有没有选过这门课
        if (userCourse != null) {
            if (userCourse.getCancelCourse() == 1) {
                course.setCurrentStudentCount(userCourses.size() + 1);
                courseMapper.updateById(course);
                return userCourseMapper.updateCancelCourse(userCourse.getId());
            } else return 0;
        }

        // 获取学生信息
        ApiResponse res = JSON.parseObject(studentApi.getStudentInfo(userId), ApiResponse.class);
        if (!res.getCode().equals(ApiResponseCodeEnum.SUCCESS.getCode())) {
            return 0;
        }
        StudentDTO studentDTO = JSON.parseObject(JSON.toJSONString(res.getData()), StudentDTO.class);

        UserCourse newSelect = new UserCourse();

        newSelect.setCourseId(courseId);
        newSelect.setCourseName(course.getCourseName());
        newSelect.setCourseCode(course.getCourseCode());
        newSelect.setTeacherUserId(course.getTeacherUserId());
        newSelect.setTeacherRealName(course.getTeacherRealName());
        newSelect.setStudentUserId(userId);
        newSelect.setStudentRealName(studentDTO.getRealname());
        newSelect.setUserScore(0);
        if (course.getCurrentStudentCount() + 1 > course.getMaxStudentCount()) {
            return 0;
        }
        course.setCurrentStudentCount(userCourses.size() + 1);
        courseMapper.updateById(course);
        return userCourseMapper.insert(newSelect);
    }

    @Override
    public Integer cancelCourse(int courseId, int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("course_id", courseId);
        map.put("student_user_id", userId);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("course_id", courseId);
        Course course = courseMapper.selectById(courseId);
        List<UserCourse> userCourses = userCourseMapper.selectByMap(map2);
        course.setCurrentStudentCount(Math.max(userCourses.size() - 1, 0));
        courseMapper.updateById(course);
        return userCourseMapper.deleteByMap(map);
    }

    @Override
    public List<UserSelectCourseDTO> selectCourses(Integer studentId) {
        Map<String, Object> map = new HashMap<>();
        map.put("student_user_id", studentId);
        List<UserCourse> userCourses = userCourseMapper.selectByMap(map);
        List<UserSelectCourseDTO> myCourses = new ArrayList<>();
        for (UserCourse userCourse : userCourses) {
            UserSelectCourseDTO dto = new UserSelectCourseDTO();
            dto.setCourseId(userCourse.getCourseId());
            dto.setCourseCode(userCourse.getCourseCode());
            dto.setCourseName(userCourse.getCourseName());
            dto.setTeacherRealname(userCourse.getTeacherRealName());
            dto.setMyScore(userCourse.getUserScore());
            Course course = courseMapper.selectById(userCourse.getCourseId());
            dto.setSectionCount(course.getSectionCount());
            dto.setCourseTime(course.getCourseTime());
            dto.setCourseProfile(course.getCourseProfile());
            dto.setTextbook(course.getTextbook());
            dto.setCreditsCount(course.getCreditsCount());
            dto.setAllScore(course.getAllScore());
            dto.setPassScore(course.getPassScore());
            myCourses.add(dto);
        }

        return myCourses;
    }

    @Override
    public UserSelectCourseDTO selectedCourseInfo(Integer studentId, Integer courseId) {
        Course course = courseMapper.selectById(courseId);
        UserCourse userCourse = userCourseMapper.selectByUserIdAndCourseId(studentId, courseId);
        UserSelectCourseDTO dto = new UserSelectCourseDTO();
        dto.setCourseId(userCourse.getCourseId());
        dto.setCourseName(userCourse.getCourseName());
        dto.setTeacherRealname(userCourse.getTeacherRealName());
        dto.setSectionCount(course.getSectionCount());
        dto.setCourseTime(course.getCourseTime());
        dto.setCourseProfile(course.getCourseProfile());
        dto.setTextbook(course.getTextbook());
        dto.setCreditsCount(course.getCreditsCount());
        dto.setAllScore(course.getAllScore());
        dto.setPassScore(course.getPassScore());
        dto.setMyScore(userCourse.getUserScore());
        return dto;
    }

    @Override
    public List<UserCourse> searchSelectedCourses(int userId) {
        QueryWrapper<UserCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_user_id", userId);
        return userCourseMapper.selectList(queryWrapper);
    }
}




